package com.mg.interceptor;

import com.mg.common.Constants;
import com.mg.model.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 */
@Configuration
public class AuthInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constants.USER_INFO);
        String url = request.getRequestURL().toString();
        if (user == null) {
            if (url.contains("/login")||url.contains("/reg") || url.lastIndexOf("/") == (url.length() - 1)) {
                return true;
            } else {
                response.sendRedirect(request.getContextPath() + "/pages/main/index.jsp");
                return false;
            }
        } else {
            if (url.contains("admin") && !Constants.ADMIN_NAME.equals(user.getUserName())) {
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }

}